package com.share.tool.generator.api.config;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;


@Slf4j
public class DirClassLoader extends URLClassLoader {
    private static URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    private static final Method ADD_URL = initAddMethod();

    private static Method initAddMethod() {
        try {
            Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            addUrl.setAccessible(true);
            return addUrl;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    static {
//		ClassLoader.registerAsParallelCapable();//是否并行加载，默认懒加载
    }

    /*必须要写的方法*/
    private DirClassLoader(URL[] urls) {
        super(urls);
    }

    public static  void loadJar(String filepath) {
        if (filepath == null) {
            return;
        } else {
            File file = new File(filepath);
            if (file.exists()) {
                log.info("正在加载目录下的jar,path=" + filepath);
                loopFile(file);
                return;
            }
        }
        log.info("jar加载失败,path=" + filepath);
    }

    /**
     *
     * 遍历目录加载jar
     *
     * @param file
     */
    private static void loopFile(File file) {
        if (file.isDirectory()) {
            File[] tmps = file.listFiles();
            for (File tmp : tmps) {
                loopFile(tmp);
            }
        } else {
            if (file.getAbsolutePath().endsWith(".jar")) {
                try {
                    ADD_URL.invoke(classLoader, file.toURI().toURL());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
